
/*
 * atmega_adc.c
 *
 * Created: 4/4/2011 17:03:26
 *  Author: morpheus
 */ 

#include "atmega_adc.h"


void initADC() 
{ 
  // adc referance voltage
  //ADMUX |= (1 << REFS0); 

  // For Aref=AVcc; 
  ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1<<ADPS0); 

  //Rrescalar div factor =128 

  // Free running
  //ADCSRA |= (1 << ADATE);

  // Left adjust ADC result to allow easy 8 bit reading  
  //ADMUX |= (1 << ADLAR);
} 

uint16_t readADC(uint8_t ch) 
{ 

  // Select ADC Channel ch must be 0-7, in case some 
  // other components will be added to the system that require ADC 
  //ch = ch & 0b00000111; 
  //ADMUX |= (ADMUX & 0xF0) | ch;

  ADMUX |= ch; 

  //Start Single conversion 
  ADCSRA |= (1 << ADSC); 

  //Wait for conversion to complete 

  //while(!(ADCSRA & (1 << ADSC))); 
  while(!bit_is_set(ADCSRA, ADIF));

  //Clear ADIF by writing one to it 
  ADCSRA |= (1<<ADIF); 

  ADMUX = 0; 

  return(ADC); 
} 

/*int main() 
{ 
  
uint16_t adc_result[4]; 
//Array to store the adc values one each of the analogue pins

float distance = 0;    
// Variable to save the distance calculated after ADC on pin0

//Initialize ADC 
InitADC(); 
Wait(); // Create a delay  

while(1) 
{ 
adc_result[0]=ReadADC(0);    
// Read Analog value from channel-0: distance 
distance =  (adc_result[0] * 2.54) / 9.7656; 
// Calculate distance 
} 
*/
